package com.inventory.controller;

import com.inventory.model.Product;
import com.inventory.service.ProductService;
import com.inventory.service.PurchaseRecordService;
import com.inventory.service.SaleRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private PurchaseRecordService purchaseRecordService;
    
    @Autowired
    private SaleRecordService saleRecordService;

    @GetMapping
    public String listProducts(Model model, @RequestParam(required = false) String keyword) {
        List<Product> products;
        
        if (keyword != null && !keyword.isEmpty()) {
            products = productService.findByNameContaining(keyword);
            model.addAttribute("keyword", keyword);
        } else {
            products = productService.findActiveProducts();
        }
        
        model.addAttribute("products", products);
        model.addAttribute("categories", productService.getAllCategories());
        return "product/list";
    }
    
    @GetMapping("/category/{category}")
    public String listProductsByCategory(@PathVariable String category, Model model) {
        model.addAttribute("products", productService.findByCategory(category));
        model.addAttribute("categories", productService.getAllCategories());
        model.addAttribute("currentCategory", category);
        return "product/list";
    }
    
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("product", new Product());
        model.addAttribute("categories", productService.getAllCategories());
        return "product/form";
    }
    
    @PostMapping("/add")
    public String addProduct(@ModelAttribute Product product, RedirectAttributes redirectAttributes) {
        try {
            // 检查条形码是否已存在
            if (product.getBarcode() != null && !product.getBarcode().isEmpty() && 
                productService.existsByBarcode(product.getBarcode())) {
                redirectAttributes.addFlashAttribute("error", "条形码已存在");
                return "redirect:/products/add";
            }
            
            productService.saveProduct(product);
            redirectAttributes.addFlashAttribute("success", "商品添加成功");
            return "redirect:/products";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品添加失败: " + e.getMessage());
            return "redirect:/products/add";
        }
    }
    
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        Optional<Product> productOpt = productService.findById(id);
        
        if (!productOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "商品不存在");
            return "redirect:/products";
        }
        
        model.addAttribute("product", productOpt.get());
        model.addAttribute("categories", productService.getAllCategories());
        return "product/form";
    }
    
    @PostMapping("/edit/{id}")
    public String updateProduct(@PathVariable Long id, @ModelAttribute Product product, RedirectAttributes redirectAttributes) {
        try {
            // 检查商品是否存在
            Optional<Product> existingProductOpt = productService.findById(id);
            if (!existingProductOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "商品不存在");
                return "redirect:/products";
            }
            
            // 检查条形码是否已被其他商品使用
            if (product.getBarcode() != null && !product.getBarcode().isEmpty()) {
                Product existingProduct = existingProductOpt.get();
                if (!existingProduct.getBarcode().equals(product.getBarcode()) && 
                    productService.existsByBarcode(product.getBarcode())) {
                    redirectAttributes.addFlashAttribute("error", "条形码已被其他商品使用");
                    return "redirect:/products/edit/" + id;
                }
            }
            
            product.setId(id);
            productService.updateProduct(product);
            redirectAttributes.addFlashAttribute("success", "商品更新成功");
            return "redirect:/products";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品更新失败: " + e.getMessage());
            return "redirect:/products/edit/" + id;
        }
    }
    
    @GetMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            productService.deleteProduct(id);
            redirectAttributes.addFlashAttribute("success", "商品删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "商品删除失败: " + e.getMessage());
        }
        return "redirect:/products";
    }
    
    @GetMapping("/detail/{id}")
    public String viewProductDetail(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        Optional<Product> productOpt = productService.findById(id);
        
        if (!productOpt.isPresent()) {
            redirectAttributes.addFlashAttribute("error", "商品不存在");
            return "redirect:/products";
        }
        
        Product product = productOpt.get();
        model.addAttribute("product", product);
        
        // 获取最近的进货记录
        model.addAttribute("purchaseRecords", purchaseRecordService.findLatestPurchasesByProductId(id));
        
        // 获取最近的销售记录
        model.addAttribute("saleRecords", saleRecordService.findLatestSalesByProductId(id));
        
        return "product/detail";
    }
    
    @GetMapping("/low-stock")
    public String viewLowStockProducts(Model model) {
        model.addAttribute("products", productService.findLowStockProducts());
        model.addAttribute("lowStock", true);
        return "product/list";
    }
} 